//
//  UserViewModel.m
//  CBT
//
//  Created by Mr.Zhang on 2018/12/3.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "UserViewModel.h"
#import "UserManager.h"

@implementation UserViewModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp{
    
    _changeUserNameCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        
        if ([NSString isBlankString:input[@"name"]]) {
            [HFStatusView showFailureMessage:kLocalizedString(@"请输入昵称",nil)];
            return [RACSignal error:nil];
        }else if ([NSString isContainsEmoji:input[@"name"]]) {
            [HFStatusView showFailureMessage:kLocalizedString(@"不能输入表情",nil)];
            return [RACSignal error:nil];
        }else if ([NSString stringWithFormat:@"%@",input[@"name"]].length > 6){
            [HFStatusView showFailureMessage:kLocalizedString(@"昵称最多6个字符",nil)];
            return [RACSignal error:nil];
        }else if (![NSString isCorrectUserName:input[@"name"]]){
            [HFStatusView showFailureMessage:kLocalizedString(@"昵称格式不正确",nil)];
            return [RACSignal error:nil];
        }
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            [UserManager changeUserNameWithUserId:input[@"ID"] nickName:input[@"name"] block:^(id data, HttpRequestResult result, NSString *msg) {
                if (result == kHttpRequestResultNormal) {
                    [HFStatusView showSuccessMessage:kLocalizedString(@"修改成功",nil)];
                    [[CBTLocalUserManager sharedInstance]refreshUserInfoDic:@{@"nickName":input[@"name"]}];
                    [subscriber sendNext:data];
                    [subscriber sendCompleted];
                }else{
                    [HFStatusView showFailureMessage:msg];
                    [subscriber sendError:nil];
                    [subscriber sendCompleted];
                }
            }];
            
            return [RACDisposable disposableWithBlock:^{
                NSLog(@"修改用户昵称操作结束了");
            }];
        }];
    }];
}


@end
